﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MultiplayerDice.Implementation;
using MultiplayerDice.Implementation.BusinessEvent;
using System.Web.Security;
using MultiplayerDice.Implementation.Infrastructure;
using System.Data;
using MultiplayerDice.Implementation.Command;

namespace MultiplayerDice.Components
{
    public partial class StartGame : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public short Diced { get; private set; }

        protected void startGameButton_Click(object sender, EventArgs e)
        {
            Diced = Dice.Throw();
            EventRaiser.Raise(new NewGameStartedCommand()
            {
                Player = Membership.GetUser().UserName,
                OpponentPlayer = opponentInput.SelectedValue,
                GameId = Guid.NewGuid(),
                DateTimeOfStart = DateTime.Now,
                Diced = Diced
            });

            viewSwitcher.ActiveViewIndex = 1;

            diceResult.Text = Diced.ToString();
            opponentResult.Text = opponentInput.SelectedValue;
        }


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            var loggedInUser = Membership.GetUser();
            if (viewSwitcher.ActiveViewIndex == 0 && loggedInUser != null)
            {
                opponentInput.DataSource = GetNames(SqlReader.Read("SELECT [Name] FROM Query_ChooseOpponent WHERE Name <> @0", loggedInUser.UserName));
                opponentInput.DataBind();
            }
        }

        private IEnumerable<object> GetNames(IEnumerable<IDataRecord> dataRecords)
        {
            var result = new List<object>();
            foreach (var record in dataRecords)
                result.Add(new { Name = record.GetString(0) });
            return result;
        }
    }
}